<template>
  <view class="page container">
    <u-form
      :model="basicForm"
      :rules="rules"
      labelPosition="top"
      ref="form"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <u-form-item label="项目名称" prop="projectId" required>
          <h-select-project-input-popup
            v-model="basicForm.projectId"
            projectStatus="2"
						queryParamType="2"
            :signUnit="sellerUnit"
            :teamId="teamId"
            class="w-100"
            placeholder="请选择项目名称"
            searchPlaceholder="请输入项目名称"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="selectProject"
          ></h-select-project-input-popup>
        </u-form-item>
				<u-form-item label="项目编号" prop="projectCode">
					<u--input disabled placeholder="请输入项目编号" v-model="basicForm.projectCode"></u--input>
				</u-form-item>
				<u-form-item label="业绩归属年度" prop="attributionYear">
				  <h-select-input-tag
				    disabled
				    class="w-100"
				    v-model="basicForm.attributionYear"
				    objectField="basicForm.attributionYear"
				    placeholder="请选择业绩归属年度"
				    border="surround"
				    dictName="yjgsnd"
				  ></h-select-input-tag>
				</u-form-item>
        <u-form-item label="项目承接人" prop="undertaker">
          <h-select-person-input-popup
            disabled
            v-model="basicForm.undertaker"
            class="w-100"
            placeholder="请选择项目承接人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="经营团队" prop="teamId">
          <h-select-team-input-popup
            disabled
            style="width: 100%"
            v-model="basicForm.teamId"
            objectField="basicForm.teamId"
            placeholder="请选择经营团队"
            border="surround"
            :tdlx="3"
          ></h-select-team-input-popup>
        </u-form-item>
        <u-form-item label="项目合同" prop="projectContract" required>
          <h-select-contract-manager-input-popup
            showName="1"
            htlx="1"
            :projectId="basicForm.projectId"
            v-model="basicForm.projectContract"
            placeholder="请选择项目合同"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="changeProjectContract"
						status="2,3,7"
          ></h-select-contract-manager-input-popup>
        </u-form-item>
        <u-form-item label="合同款项" prop="contractFund" required>
          <h-select-checkoutlist-input-popup
            :contractId="basicForm.projectContract"
						:isFinance="true"
            v-model="basicForm.contractFund"
            placeholder="请选择合同款项"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="getCheckoutInfo"
          ></h-select-checkoutlist-input-popup>
        </u-form-item>
        <u-form-item label="款项金额（元)" prop="itemMoney">
          <u--input disabled v-number-normal placeholder="请输入款项金额" v-model="basicForm.itemMoney"></u--input>
        </u-form-item>
        <u-form-item label="预计回款时间" prop="estimateRefundTime" required>
          <h-time-select
            mode="date"
            ref="estimateRefundTime"
            v-model="basicForm.estimateRefundTime"
            placeholder="请选择预计回款时间"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
				<u-form-item label="已开票金额(元)" prop="onInvoiceAmount">
					<h-money-input
						disabled
						placeholder="请输入已开票金额"
						:isMinus="false"
						v-model="basicForm.onInvoiceAmount"
						:max="99999999"
						:min="-99999999"
					></h-money-input>
				</u-form-item>
        <u-form-item label="开票金额(元)" prop="invoiceAmount" required>
					<h-money-input
						placeholder="请输入开票金额"
						:isMinus="false"
						v-model="basicForm.invoiceAmount"
						:max="isCancel=='0'?((basicForm.itemMoney==0?0:((basicForm.itemMoney && basicForm.itemMoney!=0) && (basicForm.onInvoiceAmount||basicForm.onInvoiceAmount==0) )?(Number(basicForm.itemMoney-basicForm.onInvoiceAmount)): 99999999)):0"
						:min="isCancel=='0'?0:-99999999"></h-money-input>
        </u-form-item>
      </view>

      <view class="space-x-1 mt-1" style="display: flex">
        <u-button type="primary" text="关闭" plain :loading="loading" @click="onClose"></u-button>
				<u-button type="primary" text="保存" :loading="loading" throttleTime="3000" @click="onSubmit"></u-button>
      </view>
    </u-form>
  </view>
</template>

<script>
export default {
  name: 'InvoiceForm',
  props: {
    teamId: {
      type: [String, Number],
      default: ''
    },
    sellerUnit: {
      type: [String, Number],
      default: '',
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    teamName2: {
      type: [String, Number],
      default: '',
    },
    undertaker: {
      type: [String, Number],
      default: '',
    },
    isRelProject: {
      type: Boolean,
      default: false,
    },
    datailDisabled: {
      type: Boolean,
      default: false,
    },
    index: {
      type: Number,
      default: null,
    },
    formType: {
      type: String,
      default: 'trip',
    },
		isCancel: {
      type: [String, Number],
      default: '',
    },
  },
  data() {
    return {
      loading: false,
      basicForm: {
        projectId: null,
				itemMoney: null,
				invoiceAmount: null
      },
      rules: {
        projectId: [{ required: true, message: '请选择项目!', trigger: 'change' }],
        projectContract: [{ required: true, message: '请选择项目合同!', trigger: 'change' }],
        contractFund: [{ required: true, message: '请选择合同款项!', trigger: 'change' }],
        projectProgress: [{ required: true, message: '请输入项目进度!', trigger: 'change' }],
        estimateRefundTime: [{ required: true, message: '请选择预计回款时间!', trigger: 'change' }],
				invoiceAmount: [
				  {
				    required: true,
				    pattern: /^-?(?!0\.00)(?!0$)([1-9]\d*|0)(\.\d{2})?$/,
				    message: '请输入正确开票金额!',
				    trigger: ['blur', 'change'],
				  },
				],
      },
			fpList:[],// 主表的发票信息子表
			isAdd: true,// 是否点击新增进来的
    }
  },
  methods: {
    //合同款项
		getCheckoutInfo(data){
			this.basicForm.contractFund_dictText = data.nodeName
			this.$refs.form.clearValidate('projectProgress');
			// 款项金额
			this.$set(this.basicForm, 'itemMoney', data.paymentMoney);
			//项目进度
			this.$set(this.basicForm, 'projectProgress', data.contractNodeId);
			// 开票金额
			this.$set(this.basicForm, 'onInvoiceAmount', data.invoicePaidAmount);
			let maxNum = this.isCancel=='0'?((this.basicForm.itemMoney==0?0:((this.basicForm.itemMoney && this.basicForm.itemMoney!=0) && (this.basicForm.onInvoiceAmount||this.basicForm.onInvoiceAmount==0) )?(Number(this.basicForm.itemMoney-this.basicForm.onInvoiceAmount)): 99999999)):0
			if (maxNum < Number(this.basicForm.invoiceAmount || 0)) {
				this.$set(this.basicForm, 'invoiceAmount', maxNum);
			}
		},
		selectProject(project) {
			this.$refs.form.clearValidate('projectContract');
			this.$refs.form.clearValidate('contractFund');
			this.$refs.form.clearValidate('projectProgress');
			this.basicForm.projectId_dictText = project.projectName // 项目名称
			this.$set(this.basicForm, 'projectCode', project?.finalNo || '')
			// 经营团队
			this.basicForm.teamId = project.teamName
			this.basicForm.teamId_dictText = project.teamName_dictText
			// 项目承接人
			this.basicForm.undertaker = project.undertaker
			this.basicForm.undertaker_dictText = project.undertaker_dictText
			// 所属年度
			this.basicForm.attributionYear = project.year
			this.basicForm.attributionYear_dictText = project.year_dictText
			//项目合同
			this.$set(this.basicForm, 'projectContract', null);
			//合同款项
			this.$set(this.basicForm, 'contractFund', null);
			//款项金额
			this.$set(this.basicForm, 'itemMoney', null);
			//项目进度
			this.$set(this.basicForm, 'projectProgress', null);
		},
		changeProjectContract(item){
			this.basicForm.projectContract_dictText = item.htmc
			//合同款项
			this.$set(this.basicForm, 'contractFund', null);
			//款项金额
			this.$set(this.basicForm, 'itemMoney', null);
			//项目进度
			this.$set(this.basicForm, 'projectProgress', null);
		},
		// 每次点击新增编辑重新加载发票信息子表
		loadList(list){
			this.fpList = list;
		},
		// 校验本次选择是否合法
		checkProjectAdd(){
			let projectId = this.basicForm.projectId;
			// 值拦截本次选中的项目非法的情况
			if(!!this.fpList && this.fpList.length!==0 ){
				// 是修改且只有一条数据的时候随便选 其他的直接else判断
				if(!this.isAdd && this.fpList.length===1){
					return true;
				}else {
					// 本次新增需要项目id相同
					for (let i = 0; i < this.fpList.length; i++) {
						if(this.fpList[i].projectId !== projectId){
							return false;
						}
					}
				}
			}
			return true;
		},
    reset() {
      this.$refs.form.resetFields()
    },
    async onSubmit() {
      await this.$refs.form.validate()
			this.isSubmit = true
			// 校验是否是同一个项目
			let isChecked = this.checkProjectAdd()
			if (isChecked) {
				await this.$refs.form.validate()
				if (!this.index) {
				  this.$emit('submit', [
				    {
				      id: parseInt(Math.random() * 1000000000000),
				      ...this.basicForm,
				    },
				    this.index,
				  ])
				} else {
				  this.$emit('submit', [this.basicForm, this.index])
				}
			} else{
				// 选择的项目导致子表不是同一个则提示
				this.isSubmit = false
				this.$u.toast('所选项目必须为同一个')
			}
    },
    onClose() {
      this.$emit('close')
			this.isSubmit = false
    },
  }
}
</script>

<style scoped>
.page.container {
	padding: 20px;
}
.basic-style {
	margin: 0;
	max-height: 80vh;
	overflow-y: auto;
}
.u-form-item {
	padding: 0px 8px;
}
</style>

